package org.yinxue.swing.unit.util;

import org.yinxue.swing.core.util.CloseUtil;
import org.yinxue.swing.core.util.LogUtil;

import java.awt.*;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public abstract class LogUtils {

    public static final String LOG_PREFIX = "log/";
    private static boolean isJarPath = true;

    /**
     * 写入本地日志<br>
     * 写入的日志文件路径在classpath下
     *
     * @param text
     * @param parentPath
     * @param path
     */
    public static void writeLogFile(String text, String parentPath, String path) {
        // File file = new File(parentPath, fileName);
        // 相对路径转换为绝对路径
        if (parentPath == null || "".equals(parentPath)) {
            parentPath = getAbsolutePath("") + "log";
        }
        File parentfile = new File(parentPath);
        File file = new File(parentPath, path);
        FileWriter fw = null;
        BufferedWriter bw = null;
        try {
            if (!parentfile.exists()) {
                parentfile.mkdirs();
            }
            if (!file.exists()) {
                file.createNewFile();
            }
            // 日志末尾追加
            fw = new FileWriter(file, true);
            bw = new BufferedWriter(fw);
            bw.write("\n"+text);
            bw.flush();
        } catch (Exception e) {
            LogUtil.error(LogUtils.class,"日志写入失败", e);
        } finally {
            CloseUtil.close(bw,fw);
        }
    }


    /**
     * ""为当前classpath
     *
     * @param path
     * @return
     */
    private static String getAbsolutePath(String path) {
        if (isJarPath == true){
            return getJarPath();
        }
        return Thread.currentThread().getContextClassLoader().getResource(path).getPath();
    }

    /**
     * 获取jar包所在路径
     */
    public static String getProjectPath() {
        java.net.URL url = LogUtils.class.getProtectionDomain().getCodeSource().getLocation();
        String filePath = null ;
        try {
            filePath = java.net.URLDecoder.decode(url.getPath(), "utf-8");
        } catch (Exception e) {
            LogUtil.error(LogUtils.class,"解析失败", e);
        }
        if (filePath.endsWith(".jar"))
            filePath = filePath.substring(0, filePath.lastIndexOf("/") + 1);
        File file = new File(filePath);
        filePath = file.getAbsolutePath();
        return filePath;
    }

    public static String getJarPath() {
        /**
         * 方法一：获取当前可执行jar包所在目录
         */
        String filePath = System.getProperty("java.class.path");
        String pathSplit = System.getProperty("path.separator");//得到当前操作系统的分隔符，windows下是";",linux下是":"

        /**
         * 若没有其他依赖，则filePath的结果应当是该可运行jar包的绝对路径，
         * 此时我们只需要经过字符串解析，便可得到jar所在目录
         */
        if (filePath.contains(pathSplit)) {
            filePath = filePath.substring(0, filePath.indexOf(pathSplit));
        }
        if (filePath.endsWith(".jar")) {//截取路径中的jar包名,可执行jar包运行的结果里包含".jar"
            filePath = filePath.substring(0, filePath.lastIndexOf(File.separator) + 1);
        }
        System.out.println("jar包所在目录：" + filePath);
        return filePath;
    }

    /**
     * 获得log文件夹下指定的log文件路径<br>
     * 需要加上前缀文件夹log
     *
     * @param path
     * @return
     */
    public static File getLogFile(String path) {
        return new File(getAbsolutePath(LOG_PREFIX + path));
    }

    /**
     * 针对固定路径写入空字符
     *
     * @param path
     */
    public static void writeEmpty(String logPath) {
        File pathFile = new File(getAbsolutePath(LOG_PREFIX + logPath));
        FileWriter writer = null;
        try {
            writer = new FileWriter(pathFile);
            writer.write("");
        } catch (IOException e) {
            LogUtil.error(LogUtils.class,"写入空字符失败", e);
        } finally {
            CloseUtil.close(writer);
        }
    }

    public static void openLog(String logPath) throws IOException {
        Desktop.getDesktop().open(getLogFile(logPath));
    }
}
